package cn.dgiot.fd.service.impl;

import java.sql.Timestamp;
import java.util.Date;
import java.util.UUID;

import org.springframework.beans.factory.annotation.Autowired;

import com.alibaba.fastjson.JSON;
import com.aliyuncs.AcsRequest;
import com.aliyuncs.AcsResponse;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.profile.DefaultProfile;
import com.aliyuncs.profile.IClientProfile;

import cn.dgiot.fd.contant.AliyunConfig;
import cn.dgiot.fd.model.AliyunApiLogModel;
import cn.dgiot.fd.service.IAliyunApiLogService;
import cn.dgiot.fd.service.IBaseService;


public class BaseServiceImpl implements IBaseService{

	@Autowired
	private AliyunConfig aliyunConfig;

	@Autowired
	private IAliyunApiLogService aliyunApiLogService;

	private static DefaultAcsClient acsClient;

	/**
	 * [初始化sdk]
	 * @return DefaultAcsClient
	 */
	public DefaultAcsClient getDefaultAcsClient() {
		if (acsClient == null) {
			String accessKey = aliyunConfig.accessKey;
			String accessSecret = aliyunConfig.accessSecret;
			String regionId = aliyunConfig.regionId;
			IClientProfile profile = DefaultProfile.getProfile(regionId, accessKey, accessSecret);
			acsClient = new DefaultAcsClient(profile);
		}
		return acsClient;
	}
	
	public void addAliyunApiLog(AcsRequest request,Date requsetTime,AcsResponse response,Date responseTime,boolean success) {
		addAliyunApiLog(request, requsetTime, response, responseTime, "", "", success);
	}
	
	public void addAliyunApiLog(AcsRequest request,Date requestTime,
			AcsResponse response,Date responseTime,
			String productKey, String deviceName,boolean success) {
		String actionName = request.getActionName();
		AliyunApiLogModel aliyunApiLogModel = new AliyunApiLogModel();
		aliyunApiLogModel.setId(UUID.randomUUID().toString().replace("-", ""));
		aliyunApiLogModel.setRequest(JSON.toJSONString(request));
		aliyunApiLogModel.setRequestTime(new Timestamp(requestTime.getTime()));
		aliyunApiLogModel.setResponse(JSON.toJSONString(response));
		aliyunApiLogModel.setResponseTime(new Timestamp(responseTime.getTime()));
		aliyunApiLogModel.setSuccess(String.valueOf(success));
		aliyunApiLogModel.setActionName(actionName);
		aliyunApiLogService.insertAliyunApiLog(aliyunApiLogModel);
	}

}
